#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sqlite3.h>

#define     DATABASE    "qt_test.db"
#define     PORT        5000
#define     BUFFER_SIZE 4096

static sqlite3 *db;
static int id = 1;
void handle_request(int client_socket);

int main() {
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    int opt = 1;
    int rc = sqlite3_open(DATABASE, &db);

    if (rc != SQLITE_OK) {
        fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return 1;
    }

    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    if (listen(server_socket, 10) < 0) {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }

    printf("HTTP Server is running on port %d...\n", PORT);

    while (1) {
        client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);

        if (client_socket < 0) {
            perror("accept failed");
            continue;
        }

        pid_t pid = fork();
        if (pid == 0) {  // 子进程
            close(server_socket);  // 子进程不需要监听端口
            handle_request(client_socket);
            exit(0);
        } else if (pid > 0) {  // 父进程
            close(client_socket);  // 父进程不处理客户端连接
        } else {
            perror("fork failed");
        }
    }

    close(server_socket);
    sqlite3_close(db);
    return 0;
}

void handle_request(int client_socket) 
{
    char buffer[BUFFER_SIZE];
    memset(buffer, 0, sizeof(buffer));
    sqlite3_stmt *res;
    int rc, err_flag = 1;

    read(client_socket, buffer, sizeof(buffer) - 1);
    printf("Received request:\n%s\n", buffer);

    // 简单提取请求行
    char method[8], path[256];
    sscanf(buffer, "%s %s", method, path);


    // 查找请求体（以空行 \r\n\r\n 为分隔符）
    char *body = strstr(buffer, "\r\n\r\n");
    if (body != NULL) {
        body += 4; // 跳过 \r\n\r\n
    }

    char username[100] = {0}, password[100] = {0};

    // 简单手动解析 JSON（仅限格式简单正确的情况）
    if (body) {
        char *user_ptr = strstr(body, "\"username\"");
        char *pass_ptr = strstr(body, "\"password\"");
        if (user_ptr && pass_ptr) {
            sscanf(user_ptr, "\"username\" : \"%[^\"]\"", username);
            sscanf(pass_ptr, "\"password\" : \"%[^\"]\"", password);
        }
    }

    printf("Parsed username: %s\n", username);
    printf("Parsed password: %s\n", password);

    // 准备响应
    char response[BUFFER_SIZE];
    memset(response, 0, sizeof(response));
    char sql[BUFFER_SIZE]; // sql语句

    if (strcmp(path, "/login") == 0) {
        memset(sql, 0, sizeof(sql));
        snprintf(sql, BUFFER_SIZE, "SELECT name FROM user WHERE name = '%s' AND password = '%s' LIMIT 1", username, password);

        rc = sqlite3_prepare_v2(db, sql, -1, &res, 0);

        if (rc != SQLITE_OK) {
            fprintf(stderr, "Failed to fetch data: %s\n", sqlite3_errmsg(db));
            return;
        }

        rc = sqlite3_step(res);

        if (rc == SQLITE_ROW) {
            printf("%s\n", sqlite3_column_text(res, 0));
            snprintf(response, sizeof(response),
                    "HTTP/1.1 200 OK\r\n"
                    "Content-Type: application/json\r\n\r\n" // 响应json
                    "{ \"status\": \"success\", \"message\": \"\" }\n"); // json字符串
            err_flag = 0;
        }

        sqlite3_finalize(res);

    } else if (strcmp(path, "/register") == 0) {
        memset(sql, 0, sizeof(sql));
        // 注意SQL注入
        snprintf(sql, BUFFER_SIZE, "INSERT INTO user VALUES(%d, '%s', '%s')", id, username, password);
        id++;

        rc = sqlite3_prepare_v2(db, sql, -1, &res, 0);

        if (rc != SQLITE_OK) {
            fprintf(stderr, "Failed to fetch data: %s\n", sqlite3_errmsg(db));
            return ;
        }

        rc = sqlite3_step(res);

        if (SQLITE_DONE == rc) {
            snprintf(response, sizeof(response),
                    "HTTP/1.1 200 OK\r\n"
                    "Content-Type: application/json\r\n\r\n"
                    "{ \"status\": \"success\", \"message\": \"\" }\n");
            err_flag = 0;
        }

        sqlite3_finalize(res);
    } else {
        snprintf(response, sizeof(response),
                "HTTP/1.1 404 Not Found\r\n"
                "Content-Type: text/plain\r\n\r\n"
                "Not Found\n");
    }

    // 此处逻辑需要区分登录注册，有待改善（多设置标记位）
    if (err_flag) {
        snprintf(response, sizeof(response),
                "HTTP/1.1 200 OK\r\n"
                "Content-Type: application/json\r\n\r\n"
                "{ \"status\": \"fail\", \"message\": \"用户名或密码错误\" }\n");

    }

    write(client_socket, response, strlen(response));
    close(client_socket);
}

